<template>
  <view>
    <!-- 搜索输入 -->
    <view class="search-box">
      <uni-search-bar @input="input" cancelButton="none" focus="true" radius="40"></uni-search-bar>
    </view>
    
    <!-- 搜索列表 -->
    <view class="search-result-list">
      <view class="result-item" v-for="(item, i) in searchResults" :key="i" @click="gotoGoodsList(item)">
        <text>{{item.goods_name}}</text>
        <uni-icons type="arrowright"></uni-icons>
      </view>
    </view>
    
    
    <!-- 搜索历史 -->
    <view class="search-history-box">
      <view class="search-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="20" @click="clearHistory"></uni-icons>
      </view>
      <view class="search-history">
        <uni-tag  v-for="(item,i) in searchHistory" :text="item" type="primary" :key="i" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>
    
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timerId: null, // 防抖执行函数timerId
        kw: '', // 用户搜索关键词
        searchResults: [], // 关键词搜索结果
        searchHistory: [], // 历史搜索关键词列表
      };
    },
    onLoad() {
      // 读取用户搜索历史
      this.searchHistory = JSON.parse(uni.getStorageSync('kw') || '[]') 
    },
    methods: {
      input(value){
        // 防抖清除
        clearTimeout(this.timerId)
        
        // 半秒后发起请求
        this.timerId = setTimeout(() => {
          // 防抖执行函数
          this.kw = value
          if(this.kw.trim().length === 0){
            // 清空关键词搜索结果
            this.searchResults = []
            return
          }
          
          console.log('发请求',this.kw)
          this.getSearchResults()
          
          // 保存搜索关键词
          this.saveSearchHistory()
        }, 500)
      },
      // 获取用户输入搜索结果
      async getSearchResults () {
        const {data: res} = await uni.$http.get('/goods/qsearch', {query: this.kw})
        console.log(res)
        // 数据异常判断
        if(res.meta.status !== 200) return uni.$showMsg()
        // 设置页面数据
        this.searchResults = res.message
      },
      // 点击搜索结果跳转到商品列表页
      gotoGoodsList(item){
        console.log(item)
        uni.navigateTo({
          url: `/subpkg/goods_list/goods_list?goods_id=${item.goods_id}`
        })
      },
      // 保存搜索关键词
      saveSearchHistory() {
        // 去数组中查询是否之前搜索过
        // 是 把原来的删除，追加到数组开头
        // 否 追加到数组开头
        const index = this.searchHistory.indexOf(this.kw)
        console.log(index)
        if(index > -1){// 找到了
          // 1 删除找到的元素
          this.searchHistory.splice(index, 1)
          console.log(this.searchHistory)
          
          // 2 再把元素放回去
          // this.searchHistory.unshift(this.kw) // 不保险
          this.searchHistory = [this.kw, ...this.searchHistory]
        }else{// 没找到
          // this.kw
          this.searchHistory.unshift(this.kw)
        }
        
        // 保存搜索关键词到本地
        uni.setStorageSync('kw', JSON.stringify(this.searchHistory))
      },
      clearHistory(){
        this.searchHistory = []
        // 清空本地存储中记录的搜索历史
        uni.setStorageSync('kw', '[]')
        // 或者
        // uni.removeStorageSync('kw')
      },
      gotoGoodsList(item) {
        uni.navigateTo({
          url: `/subpkg/goods_list/goods_list?query=${item}`
        })
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    background-color: #c00000;
    position: sticky;
    top: 0
  }
  
  .search-result-list {
    .result-item {
      display: flex;
      justify-content: space-between;
      height: 80rpx;
      align-items: center;
      border-bottom: 2px solid #efefef;
      // margin: 0 16rpx;
      padding: 0 16rpx;
      text {
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        font-size: 24rpx;
      }
    }
  }
  
  .search-history-box {
    .search-title {
      height: 80rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #efefef;
      padding: 0 16rpx;
    }
    .search-history {
      height: 80rpx;
      display: flex;
      align-items: center;
      .uni-tag {
        margin: 10rpx;
      }
      
    }
  }
</style>
